package tech.aistar.controller;

import com.github.pagehelper.PageInfo;
import tech.aistar.pojo.Phone;
import tech.aistar.pojo.PhoneType;
import tech.aistar.service.IPhoneService;
import tech.aistar.service.IPhoneTypeService;
import tech.aistar.service.impl.PhoneServiceImpl;
import tech.aistar.service.impl.PhoneTypeServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * @author Ray
 * @version 1.0
 * @description:本类用来演示:
 * @date 2019/9/5  20:54
 */
@WebServlet(urlPatterns = "/phone/list")
public class PhoneListAction extends HttpServlet {
    private IPhoneTypeService phoneTypeService = new PhoneTypeServiceImpl();
    private IPhoneService phoneService = new PhoneServiceImpl();

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //处理中文乱码
        req.setCharacterEncoding("utf-8");

        //接收查询的参数
        String name = req.getParameter("name");//手机名称进行模糊查询
        //数据回显
        req.setAttribute("name", name == null ? "" : name);

        //接收手机的类型
        String typeId = req.getParameter("typeId");//手机类型
        //====分页===
        String pageNum = req.getParameter("pageNum");
        String pageSize = req.getParameter("pageSize");

        //第一次进入
        pageNum = pageNum == null?"1":pageNum;
        pageSize = pageSize == null?"2":pageSize;


        Integer tid = null;
        if (typeId==null || "-1".equals(typeId)){
            tid=null;
        }else{
            tid=Integer.valueOf(typeId);
            //数据回显
            req.setAttribute("typeId",tid);
        }

        //调用service
//        List<Phone> phoneList = phoneService.findAll(name,tid);
//        //将手机信息放到request作用域中
//        req.setAttribute("phoneList",phoneList);

        PageInfo<Phone> pageInfo = phoneService.findAll(name,tid,Integer.valueOf(pageNum),Integer.valueOf(pageSize));
        req.setAttribute("pageInfo",pageInfo);

        List<PhoneType> phoneTypeList = phoneTypeService.findAll();
        req.setAttribute("phoneTypeList",phoneTypeList);


        //转发到nav 由nav转发到listView
        req.getRequestDispatcher("/prj/index/phonelist.jsp").forward(req,resp);
    }
}
